// src/server/server.cpp
#include "server.h"
#include "client_handler.h"
#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>

// 构造函数
ChatServer::ChatServer(int port) : port(port), running(false) {}

// 析构函数
ChatServer::~ChatServer() {
    stop();
    for (auto handler : clients) {
        delete handler;
    }
}

// 启动服务器
bool ChatServer::start() {
    // 创建socket
    server_socket = socket(AF_INET, SOCK_STREAM, 0);
    if (server_socket == -1) {
        std::cerr << "Failed to create socket" << std::endl;
        return false;
    }
    
    // 设置socket选项
    int opt = 1;
    if (setsockopt(server_socket, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt)) == -1) {
        std::cerr << "Failed to set socket options" << std::endl;
        close(server_socket);
        return false;
    }
    
    // 绑定socket
    sockaddr_in server_addr;
    memset(&server_addr, 0, sizeof(server_addr));
    server_addr.sin_family = AF_INET;
    server_addr.sin_addr.s_addr = INADDR_ANY;
    server_addr.sin_port = htons(port);
    
    if (bind(server_socket, (struct sockaddr*)&server_addr, sizeof(server_addr)) == -1) {
        std::cerr << "Failed to bind socket" << std::endl;
        close(server_socket);
        return false;
    }
    
    // 监听连接
    if (listen(server_socket, 5) == -1) {
        std::cerr << "Failed to listen on socket" << std::endl;
        close(server_socket);
        return false;
    }
    
    std::cout << "Server started on port " << port << std::endl;
    running = true;
    
    // 接受客户端连接
    accept_clients();
    
    return true;
}

// 停止服务器
void ChatServer::stop() {
    if (running) {
        running = false;
        close(server_socket);
        std::cout << "Server stopped" << std::endl;
    }
}

// 接受客户端连接
void ChatServer::accept_clients() {
    while (running) {
        sockaddr_in client_addr;
        socklen_t client_addr_len = sizeof(client_addr);
        
        // 接受客户端连接
        int client_socket = accept(server_socket, (struct sockaddr*)&client_addr, &client_addr_len);
        if (client_socket == -1) {
            std::cerr << "Failed to accept client connection" << std::endl;
            continue;
        }
        
        std::cout << "New client connected" << std::endl;
        
        // 创建新用户
        userManager.addUser(User("user" + std::to_string(client_socket), client_socket));
        
        // 创建客户端处理器并启动线程
        ClientHandler* handler = new ClientHandler(client_socket, this);
        handler->start();
        add_client_handler(handler);
    }
}

// 广播消息给所有客户端
void ChatServer::broadcast_message(const std::string& message, int sender_socket) {
    std::cout << "Server received message: " << message << std::endl; // 新增，显示服务器接收到的消息
    auto users = userManager.getUsers();
    
    for (const auto& user : users) {
        if (user.getSocketFd() != sender_socket) {
            send_message(user.getSocketFd(), message);
        }
    }
}

// 发送消息给特定客户端
void ChatServer::send_message(int client_socket, const std::string& message) {
    ssize_t bytes_sent = write(client_socket, message.c_str(), message.length());
    if (bytes_sent == -1) {
        std::cerr << "Failed to send message to client" << std::endl;
    }
}

// 移除客户端
void ChatServer::remove_client(int client_socket) {
    userManager.removeUser(client_socket);
    
    // 查找并删除对应的客户端处理器
    for (auto it = clients.begin(); it != clients.end(); ++it) {
        if ((*it)->getClientSocket() == client_socket) {
            delete *it;
            clients.erase(it);
            break;
        }
    }
    
    close(client_socket);
    std::cout << "Client disconnected" << std::endl;
}

// 添加客户端处理器
void ChatServer::add_client_handler(ClientHandler* handler) {
    clients.push_back(handler);
}    

int main() {
    std::cout << "Starting chat server..." << std::endl;
    
    // 创建并启动服务器（使用端口8080，可根据需要修改）
    ChatServer server(8080);
    if (server.start()) {
        std::cout << "Server running. Press Enter to stop..." << std::endl;
        std::cin.get();  // 等待用户输入，阻止主函数退出
        server.stop();
    }
    
    return 0;
}